from flask import Flask, request, Response
from flask_cors import CORS
from openai import OpenAI
import mysql.connector
from datetime import datetime
import json

app = Flask(__name__)
CORS(app)

# Configuration
BASE_URL = "http://localhost:8000/v1"
API_KEY = "f2cf7eb283c7f91c.45e1bd5aa391e21e3d04ace1d73ca10f"
MODEL_ID = "66d6a4447af1409538b17952"

# Database configuration
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': 'mf4B0zc4bFQGQQRcNUze',
    'database': 'ai_chat_db'
}

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)

def get_db_connection():
    return mysql.connector.connect(**DB_CONFIG)

@app.route('/api3/chat', methods=['POST'])
def chat():
    data = request.json
    user_message = data['message']

    def generate():
        # Call AI service with streaming
        response = client.chat.completions.create(
            model=MODEL_ID,
            messages=[{"role": "user", "content": user_message}],
            stream=True
        )

        full_response = ""
        for chunk in response:
            if chunk.choices[0].delta.content is not None:
                content = chunk.choices[0].delta.content
                full_response += content
                yield f"data: {json.dumps({'content': content})}\n\n"

        # Save conversation to database
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO conversations (user_message, ai_response, timestamp)
            VALUES (%s, %s, %s)
        """, (user_message, full_response, datetime.now()))
        conn.commit()
        conn.close()

    return Response(generate(), content_type='text/event-stream')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)